package com.xywl.escort.view.address;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.base.BaseActivity;
import com.xywl.escort.bean.AddrBean;
import com.xywl.escort.bean.AddrReq;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.JsonCityBean;
import com.xywl.escort.utils.GetJsonDataUtil;
import com.xywl.escort.utils.NetworkUtil;
import com.xywl.escort.utils.ToastUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dagger.android.AndroidInjection;
import timber.log.Timber;

@Route(path = "/xy/address/add")
public class AddAddressActivity extends BaseActivity implements AddAddressContract.View {

    @BindView(R.id.tv_select_address)
    TextView mTvSelectAddress;

    @Inject
    AddAddressContract.Presenter mPresenter;
    @BindView(R.id.edit_name)
    EditText mEditName;
    @BindView(R.id.edit_phone)
    EditText mEditPhone;
    @BindView(R.id.edit_detail_address)
    EditText mEditDetailAddress;

    @Autowired
    public AddrBean bean;
    @Autowired
    public int type;

    private ThreadFactory nameThreadFactory = new ThreadFactoryBuilder().setNameFormat("").build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MICROSECONDS, new LinkedBlockingQueue<Runnable>(1024), nameThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    private ArrayList<JsonCityBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;
    private String mProvinceName;
    private String mCityName;
    private String mDistrictName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ARouter.getInstance().inject(this);
        ButterKnife.bind(this);

        showBackButton();
        showTitleLine();

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        if (type == 0) {
            setTitleText("添加新地址");
        } else {
            setTitleText("编辑地址");
        }

        mPresenter.takeView(this);

        Timber.tag("AddAddressActivity").e("bean=" + bean);
        if (null != bean) {
            mEditName.setText(bean.contacts);
            mEditPhone.setText(bean.contactNumber + "");
            mProvinceName = bean.province;
            mCityName = bean.city;
            mDistrictName = bean.district;
            String address = mProvinceName + mCityName + mDistrictName;
            mTvSelectAddress.setText(address);
            mEditDetailAddress.setText(bean.address);
        }
    }

    @OnClick({R.id.tv_select_address, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_select_address: {
                hideInputMethod();
                if (isLoaded) {
                    showPickerView();
                }
            }
            break;
            case R.id.btn_confirm: {
                submit();
            }
            break;
            default:
                break;
        }
    }

    private void submit() {
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error);
            return;
        }
        AddrReq req = new AddrReq();
        String contacts = mEditName.getText().toString();
        String contactNumber = mEditPhone.getText().toString();
        String address = mEditDetailAddress.getText().toString();
        if (checkInfo(mProvinceName, mCityName, mDistrictName, address, contacts, contactNumber)) {
            req.province = mProvinceName;
            req.city = mCityName;
            req.district = mDistrictName;
            req.address = address;
            req.contacts = contacts;
            req.contactNumber = contactNumber;
            if (type == 0) {
                mPresenter.addUserShippingAddress(req);
            } else {
                req.id = bean.id;
                req.isDefault = bean.isDefault;
                mPresenter.updateUserShippingAddress(req);
            }
        }
    }

    private boolean checkInfo(String province, String city, String district, String address, String contacts, String contactNumber) {
        if (TextUtils.isEmpty(contacts)) {
            ToastUtil.showTip(this, "联系人不能为空");
            return false;
        } else if (TextUtils.isEmpty(contactNumber)) {
            ToastUtil.showTip(this, "联系电话不能为空");
            return false;
        } else if (TextUtils.isEmpty(province) || TextUtils.isEmpty(city) || TextUtils.isEmpty(district)) {
            ToastUtil.showTip(this, "地址选择不能为空");
            return false;
        } else if (TextUtils.isEmpty(address)) {
            ToastUtil.showTip(this, "地址输入不能为空");
            return false;
        }
        return true;
    }

    /**
     * 弹出选择器
     */
    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this,
                new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        mProvinceName = options1Items.get(options1).getPickerViewText();
                        mCityName = options2Items.get(options1).get(options2);
                        mDistrictName = options3Items.get(options1).get(options2).get(options3);
                        String city = mProvinceName + mCityName + mDistrictName;

                        mTvSelectAddress.setText(city);
                    }
                })
                //.setTitleText("城市选择")
                .setTitleBgColor(Color.WHITE)
                .setBgColor(Color.WHITE)
                // 默认选中项
                // .setSelectOptions(1, 0, 4)
                .setSubmitColor(ContextCompat.getColor(this, R.color.normal_text_color))
                .setCancelColor(ContextCompat.getColor(this, R.color.normal_text_color))
                .setDividerColor(ContextCompat.getColor(this, R.color.line_color))
                //设置选中项文字颜色
                .setTextColorCenter(ContextCompat.getColor(this, R.color.main_body_major_color))
                .setTextColorOut(ContextCompat.getColor(this, R.color.main_body_prompt_color))
                .setContentTextSize(20)
                .build();

        //三级选择器
        pvOptions.setPicker(options1Items, options2Items, options3Items);
        pvOptions.show();
    }

    private void hideInputMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm && imm.isActive()) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void addAddressSuccess(BaseResp resp) {
        ToastUtil.showTip(this, "添加收货地址成功");
        finish();
    }

    @Override
    public void addAddressFailure(String msg) {
        ToastUtil.showTip(this, msg);
    }

    @Override
    public void updateAddressSuccess(BaseResp resp) {
        ToastUtil.showTip(this, "修改收货地址成功");
        finish();
    }

    @Override
    public void updateAddressFailure(String msg) {
        ToastUtil.showTip(this, msg);
    }

    private class ThreadFactoryBuilder implements ThreadFactory {

        private String mNameFormat;

        private ThreadFactoryBuilder() {
        }

        private ThreadFactoryBuilder setNameFormat(String nameFormat) {
            this.mNameFormat = nameFormat;
            return this;
        }

        public ThreadFactoryBuilder build() {
            return this;
        }

        @Override
        public Thread newThread(@NonNull Runnable runnable) {
            return new Thread(runnable, mNameFormat + "-Thread-");
        }
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case MSG_LOAD_DATA:
                    singleThreadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            // 写子线程中的操作,解析省市区数据
                            initJsonData();
                        }
                    });
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    break;
                default:
                    break;

            }
            return false;
        }
    });

    /**
     * 解析数据
     */
    private void initJsonData() {
        // 获取assets目录下的json文件数据
        String jsonData = new GetJsonDataUtil().getJson(this, "city.json");
        //用Gson转成实体
        ArrayList<JsonCityBean> jsonBeanList = parseData(jsonData);

        // 添加省份数据
        // 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，PickerView会通过getPickerViewText方法获取字符串显示出来。
        options1Items = jsonBeanList;

        //遍历省份
        for (int i = 0; i < jsonBeanList.size(); i++) {
            // 该省的城市列表（第二级）
            ArrayList<String> cityList = new ArrayList<>();
            // 该省的所有地区列表（第三极）
            ArrayList<ArrayList<String>> provinceAreaList = new ArrayList<>();

            // 遍历该省份的所有城市
            for (int c = 0; c < jsonBeanList.get(i).children.size(); c++) {
                String cityName = jsonBeanList.get(i).children.get(c).name;
                // 添加城市
                cityList.add(cityName);

                // 该城市的所有地区列表
                ArrayList<String> cityAreaList = new ArrayList<>();

                // 如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBeanList.get(i).children.get(c).children == null
                        || jsonBeanList.get(i).children.get(c).children.size() == 0) {
                    cityAreaList.add("");
                } else {
                    // 该城市对应地区所有数据
                    for (int d = 0; d < jsonBeanList.get(i).children.get(c).children.size(); d++) {
                        JsonCityBean.ChildrenBeanX.ChildrenBean bean = jsonBeanList.get(i).children.get(c).children.get(d);
                        String areaName = bean.name;
                        // 添加该城市所有地区数据
                        cityAreaList.add(areaName);
                    }
                }
                // 添加该省所有地区数据
                provinceAreaList.add(cityAreaList);
            }

            // 添加城市数据
            options2Items.add(cityList);

            // 添加地区数据
            options3Items.add(provinceAreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    /**
     * Gson 解析
     *
     * @param result
     * @return
     */
    private ArrayList<JsonCityBean> parseData(String result) {
        ArrayList<JsonCityBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonCityBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonCityBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
            e.printStackTrace();
        }
        return detail;
    }
}
